package com.beibei.framework.aspect;

import javax.annotation.Resource;
import javax.xml.ws.WebServiceContext;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import com.beibei.file.bean.ServiceFile;
import com.beibei.framework.logger.ILogger;
import com.beibei.framework.logger.LoggerFactory;

/**
 * JDBC执行语句拦截器
 * 
 * @author 309814490@qq.com
 * @since 2014-02-14
 */
@Aspect
public class ServiceAspect extends BaseAspect {
	@Resource
	private WebServiceContext context;

	/**
	 * 获取日志对象
	 */
	protected ILogger getServiceLog() {
		return LoggerFactory.getServiceLog();
	}

	@Pointcut("execution(* com.beibei.core.*.service..*.*(..))")
	private void pointCutMethod() {
	}

	@Around("pointCutMethod()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

		// 获取JdbcFile对象
		ServiceFile serviceFile = this.getServiceFile(pjp);
		serviceFile.setStartTime(System.currentTimeMillis());

		// 调用服务
		Object object = pjp.proceed();

		// 设置服务调用结束时间
		serviceFile.setEndTime(System.currentTimeMillis());
		getServiceLog().file(serviceFile.getValue());

		return object;
	}

	/**
	 * 创建JdbcFile对象
	 * 
	 * @param args
	 * @return
	 */
	private ServiceFile getServiceFile(ProceedingJoinPoint pjp) {
		ServiceFile serviceFile = new ServiceFile();

		try {
			String value = pjp.toShortString().substring(10);
			String service = value.substring(0, value.indexOf("."));
			String method = value.substring(service.length() + 1, value.indexOf("("));

			serviceFile.setClassName(service); // 执行类
			serviceFile.setClassMethod(method); // 执行方法
			serviceFile.setMethodParams(this.getServiceParams(pjp.getArgs())); // 方法参数
			serviceFile.setClientIp(super.getUserIp(context)); // 客户端IP
		} catch (Exception e) {
			getCommonLog().error("getJdbcFile", "error", e);
		}

		return serviceFile;
	}

	/**
	 * 获取服务调用参数
	 * 
	 * @param pjp
	 * @return
	 */
	protected String getServiceParams(Object[] args) {
		if (args == null) {
			return "";
		}

		StringBuilder value = new StringBuilder();
		for (Object arg : args) {
			value.append(arg).append(",");
		}
		return value.toString();
	}

}
